package com.ycsj.goldmedalnewconcept.student.activity;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.doubleclick.AntiShake;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.activity.FollowReadDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.adapter.UnitGvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.UnitGvInfo;
import com.ycsj.goldmedalnewconcept.common.bean.UnitInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LayoutUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherCreateHomeworkActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherTKAssignHomeworkActivity;
import com.ycsj.goldmedalnewconcept.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 学生端单元选择界面
 * Created by Administrator on 2019/2/20 0020.
 */

public class ChooseStudentUnitActivity extends BaseActivity {
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;

    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    @BindView(R.id.scrollview)
    MyScrollView scrollView;
    @BindView(R.id.rl_contain)
    RelativeLayout rlContain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.mgv)
    MyGridView mgv;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;

    //展示单元栏目的数据格式
    private List<UnitGvInfo> unitDatas;

    //背景图的设计宽高
    private int width = 750;
    private int height = 10672;

    //展示单元选项的GridView适配器
    private UnitGvAdapter gvAdapter;

    //用于存放所有布局参数
    private List<Integer> paramsMarginlefts;
    private List<Integer> paramsMargintops;
    private int screenWidth;
    //用于放置所有按钮的线性布局的高度
    private int llheight;

    //每个Unit单元的TextView的大小
    private int itemSize = 48;

    //添加Unit单元的布局参数
    private RelativeLayout.LayoutParams lp;

    //所有的单元信息
    private List<UnitInfo.LessonListBean> lessons;

    //页面请求参数
    private String acc, role, apptoken;

    //记录点击的单元的索引位置
    private int index;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_choose_unit;
    }

    @Override
    protected void init() {

        //沉浸式
        initStateBar();

        //初始化标题
        initTitle();

        //初始化我的成绩按钮
        initEdit();

        //初始化请求参数
        initParams();

        //初始化单元导航栏
        initGv();

        //动态配置滚动布局的宽高
        initParamsBg();

        //请求页面数据
        http();

    }


    /**
     * 初始化请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
    }

    /**
     * 请求页面数据
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "14");
        map.put("acc", acc);
        map.put("role", role);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        LogUtils.iTag("test", HttpAddress.CHOOSESTUNIT + "?&type=14&acc=" + acc + "&role="
                + role + "&platform=2&apptoken=" + apptoken);

        HttpUtils.post(HttpAddress.CHOOSESTUNIT, map, this, new HttpCallBack<UnitInfo>() {
            @Override
            public void onSuccess(UnitInfo info) {
                rlLoading.setVisibility(View.GONE);
                rlContent.setVisibility(View.VISIBLE);
                rlContain.setVisibility(View.VISIBLE);
                scrollView.setVisibility(View.VISIBLE);

                if (null != info && "200".equals(info.getState())) {

                    //刷新本地保存的学生老师和学生班级
                    SPUtil.put(ChooseStudentUnitActivity.this, SpKeys.TEACHER, info.getF_teacher());

                    //保存自己的班级ID
                    SPUtil.put(ChooseStudentUnitActivity.this, SpKeys.CLASSNUM, info.getF_classnum());

                    //获取所有的Lessons
                    lessons = info.getLesson_list();

                    //动态计算每个按钮的布局参数宽和高
                    initPositon();

                    //设置ScrollView的滚动监听事件
                    initScrollListener();

                } else {
                    ToastUtils.showShort(BaseApplication.STATEERROE + info.getState());
                }
            }

            @Override
            public void onError(String e) {
                rlLoading.setVisibility(View.GONE);
                rlContain.setVisibility(View.GONE);
                rlContent.setVisibility(View.GONE);
                scrollView.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });


    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("选择单元");
    }

    /**
     * 历史成绩的按钮
     */
    private void initEdit() {
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(36), UiUtils.dp2px(36));
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.st_myscore);
        lvEdit.setVisibility(View.VISIBLE);
    }


    /**
     * 动态设置背景图的宽高
     */
    private void initParamsBg() {
        screenWidth = ScreenUtils.getScreenWidth(this);
        //计算高度,根据设计图的宽高比来动态配置
        llheight = screenWidth * height / width;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(screenWidth, llheight);
        rlContain.setLayoutParams(lp);
    }

    /**
     * 动态计算72个单元的布局宽和高
     */
    private void initPositon() {
        paramsMarginlefts = LayoutUtils.getMarinLefts(screenWidth);
        paramsMargintops = LayoutUtils.getMarinTops(llheight);

        //动态添加按钮布局
        if (paramsMarginlefts.size() != 0 && paramsMargintops.size() != 0) {

            for (int i = 1; i <= paramsMargintops.size(); i++) {

                TextView tv = (TextView) View.inflate(this, R.layout.unit_item_tv, null);

                lp = new RelativeLayout.LayoutParams(UiUtils.dp2px(itemSize), UiUtils.dp2px(itemSize));
                lp.topMargin = paramsMargintops.get(i - 1);
                lp.leftMargin = paramsMarginlefts.get(i - 1);
                tv.setText((73 - i) + "");

                //配置TextView的paddingleft和paddingtop,确保文字居中
                if (i > 63 && i <= paramsMargintops.size()) {
                    //文字为1到9时
                    tv.setPadding(UiUtils.dp2px(15), UiUtils.dp2px(7), 0, 0);
                } else {
                    //文字为两位数数
                    tv.setPadding(UiUtils.dp2px(11), UiUtils.dp2px(7), 0, 0);
                }

                //给每个TextView添加一个表示
                tv.setTag(73 - i);

                //这里还需要根据服务器返回的状态来设置Unit的背景以及是否可以点击
                if ("0".equals(lessons.get(72 - i).getEnable())) {
                    //不允许 上锁背景
                    tv.setBackgroundResource(R.drawable.tv_lock);
                } else if ("1".equals(lessons.get(72 - i).getEnable())) {
                    //允许访问 非上锁背景
                    tv.setBackgroundResource(R.drawable.tv_unit_open);

                    //根据是否有错题给每个单元设置错题的标识
                    if (!"0".equals(lessons.get(72 - i).getWrong_num())) {
                        //有错题给错题的标识
                        tv.setBackgroundResource(R.drawable.tv_unit_error);
                    }
                }


                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        index = (int) view.getTag();

                        if ("0".equals(lessons.get(index - 1).getEnable())) {
                            //不允许点击游客只允许点击1-4单元
                            ToastUtils.showShort("您没有权限，请联系老师");
                        } else if ("1".equals(lessons.get(index - 1).getEnable())) {

                            //允许点击
                            YuXiAndFuXiAcitivity.goActivity(ChooseStudentUnitActivity.this, lessons.get(index - 1), index + "", AccountUtils.getClassNum(ChooseStudentUnitActivity.this));

                        }
                    }
                });

                rlContain.addView(tv, lp);
            }
        }
    }

    /**
     * 初始化单元导航栏
     */
    private void initGv() {

        unitDatas = new ArrayList<>();
        UnitGvInfo oneUnitGvInfo = new UnitGvInfo(R.drawable.one_select, R.drawable.one_unselect, true);
        UnitGvInfo twoUnitGvInfo = new UnitGvInfo(R.drawable.two_select, R.drawable.two_unselect, false);
        UnitGvInfo threeUnitGvInfo = new UnitGvInfo(R.drawable.three_select, R.drawable.three_unselect, false);
        UnitGvInfo fourUnitGvInfo = new UnitGvInfo(R.drawable.four_select, R.drawable.four_unselect, false);
        unitDatas.add(oneUnitGvInfo);
        unitDatas.add(twoUnitGvInfo);
        unitDatas.add(threeUnitGvInfo);
        unitDatas.add(fourUnitGvInfo);

        gvAdapter = new UnitGvAdapter(this, unitDatas, R.layout.item_gv_unit);

        mgv.setAdapter(gvAdapter);

        //条目点击事件
        mgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                //根据点击的条目让ScrollView滚动到指定位置
                switch (position) {
                    case 0:
                        //滚动到底部
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 1://顶部停留在19单元
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(53);
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(ChooseStudentUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 2://37
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(35);
                                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(ChooseStudentUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 3:
                        //滚动到顶部
                        scrollView.fullScroll(ScrollView.FOCUS_UP);
                        break;
                }

                if (unitDatas.get(position).isSelected) {
                    return;
                } else {
                    sysGvState(position);
                }
            }
        });
    }

    /**
     * ScrollView的滚动监听事件
     */
    private void initScrollListener() {

        //初次进入的时候让ScrollView滚动到底部
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

        //滚动监听
        scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                //判断滚动距离,同步顶部Unit单元的同步状态

                TextView tv53 = (TextView) rlContain.getChildAt(53); //对应19
                int top53Distance = tv53.getTop() - ScreenUtils.getScreenHeight(ChooseStudentUnitActivity.this) + UiUtils.dp2px(80);

                TextView tv35 = (TextView) rlContain.getChildAt(35);//对应3
                int top35Distance = tv35.getTop() - ScreenUtils.getScreenHeight(ChooseStudentUnitActivity.this) + UiUtils.dp2px(80);

                TextView tv17 = (TextView) rlContain.getChildAt(17);//对应3
                int top17Distance = tv17.getTop() - ScreenUtils.getScreenHeight(ChooseStudentUnitActivity.this) + UiUtils.dp2px(80);

                //从下往上滑
                if (scrollY > top53Distance) {
                    //1-1选中
                    sysGvState(0);
                } else if (scrollY > top35Distance) {
                    //1-2选中,滚动距离为9978-5615 对应的是53-35
                    sysGvState(1);
                } else if (scrollY > top17Distance) {
                    //1-3选中,滚动距离为5615-221 对应的是35-17
                    sysGvState(2);
                } else if (scrollY > 0) {
                    //1-4选中
                    sysGvState(3);
                }
            }
        });
    }

    /**
     * @param pos
     */
    private void sysGvState(int pos) {
        for (int i = 0; i < unitDatas.size(); i++) {
            if (i == pos) {
                unitDatas.get(i).isSelected = true;
            } else {
                unitDatas.get(i).isSelected = false;
            }
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void clickEvent(View v) {
        if (AntiShake.check(v)) {
            ToastUtils.showShort("点击过快");
        } else {
            switch (v.getId()) {
                case R.id.iv_back:
                    //返回
                    finish();
                    break;
                case R.id.lv_edit:
                    //我的成绩
                    UiUtils.startActivity(this, StuentMyScoreActivity.class);
                    break;
            }
        }
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo) {

            //草稿箱保存成功及练习发布成功，关闭单元选择界面
            if (busInfo.type == TeacherCreateHomeworkActivity.SUBMITSUC || busInfo.type == TeacherTKAssignHomeworkActivity.SUBMITREF) {
                finish();
            } else if (FollowReadDetailsActivity.FINISH == busInfo.type) {
                //同步课文跟读状态
                if (null != lessons.get(index - 1) && !"1".equals(lessons.get(index - 1).getRepeat_done())) {
                    lessons.get(index - 1).setRepeat_done("1");
                }
            }
        }
    }
}
